package cn.lili.modules.goods.serviceimpl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.properties.RocketmqCustomProperties;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.activity.entity.vo.ActivityVO;
import cn.lili.modules.activity.mapper.ActivityMapper;
import cn.lili.modules.goods.entity.dos.*;
import cn.lili.modules.goods.entity.dto.*;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsStatusEnum;
import cn.lili.modules.goods.entity.vos.*;
import cn.lili.modules.goods.mapper.GoodsMapper;
import cn.lili.modules.goods.service.*;
import cn.lili.modules.goods.util.ExcelUtil;
import cn.lili.modules.member.entity.dos.Extension;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.MemberEvaluation;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.enums.EvaluationGradeEnum;
import cn.lili.modules.member.entity.vo.PartnerVO;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.modules.member.service.MemberEvaluationService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.member.serviceimpl.ExtensionServiceImpl;
import cn.lili.modules.store.entity.dos.FreightTemplate;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.enums.StoreStatusEnum;
import cn.lili.modules.store.entity.vos.StoreSearchParams;
import cn.lili.modules.store.entity.vos.StoreVO;
import cn.lili.modules.store.service.FreightTemplateService;
import cn.lili.modules.store.service.StoreDetailService;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.system.entity.dos.Region;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.GoodsSetting;
import cn.lili.modules.system.entity.enums.SettingEnum;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.system.service.SettingService;
import cn.lili.mybatis.BaseEntity;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.rocketmq.RocketmqSendCallbackBuilder;
import cn.lili.rocketmq.tags.GoodsTagsEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品业务层实现
 *
 * @author pikachu
 * @since 2020-02-23 15:18:56
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

	/**
	 * 分类
	 */
	@Autowired
	private CategoryService categoryService;
	/**
	 * 设置
	 */
	@Autowired
	private SettingService settingService;
	/**
	 * 商品相册
	 */
	@Autowired
	private GoodsGalleryService goodsGalleryService;
	/**
	 * 商品规格
	 */
	@Autowired
	private GoodsSkuService goodsSkuService;
	/**
	 * 店铺详情
	 */
	@Autowired
	private StoreService storeService;
	/**
	 * 会员评价
	 */
	@Autowired
	private MemberEvaluationService memberEvaluationService;
	/**
	 * rocketMq
	 */
	@Autowired
	private RocketMQTemplate rocketMQTemplate;
	/**
	 * rocketMq配置
	 */
	@Autowired
	private RocketmqCustomProperties rocketmqCustomProperties;

	@Autowired
	private FreightTemplateService freightTemplateService;

	@Autowired
	private Cache<GoodsVO> cache;
	@Autowired
	private GoodsImgDictService goodsImgDictService;
	@Autowired
	private StoreDetailService storeDetailService;

	@Autowired
	private GoodsMapper goodsMapper;

	@Autowired
	private GoodsSkuService getGoodsSkuService;

	@Autowired
	private RegionService regionService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private EextensionService eextensionService;

	@Autowired
	private PartnerService partnerService;

	@Autowired
	private ActivityMapper activityMapper;

	@Override
	public List<Goods> getByBrandIds(List<String> brandIds) {
		LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.in(Goods::getBrandId, brandIds);
		return list(lambdaQueryWrapper);
	}

	@Override
	public void underStoreGoods(String storeId) {
		// 获取商品ID列表
		List<String> list = this.baseMapper.getGoodsIdByStoreId(storeId);
		// 下架店铺下的商品
		updateGoodsMarketAble(list, GoodsStatusEnum.DOWN, "店铺关闭");
	}

	/**
	 * 更新商品参数
	 *
	 * @param goodsId
	 *            商品id
	 * @param params
	 *            商品参数
	 */
	@Override
	public void updateGoodsParams(String goodsId, String params) {
		LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(Goods::getId, goodsId);
		updateWrapper.set(Goods::getParams, params);
		this.update(updateWrapper);
	}

	@Override
	public final long getGoodsCountByCategory(String categoryId) {
		QueryWrapper<Goods> queryWrapper = Wrappers.query();
		queryWrapper.like("category_path", categoryId);
		queryWrapper.eq("delete_flag", false);
		return this.count(queryWrapper);
	}

	@Override
	public void addGoods(GoodsOperationDTO goodsOperationDTO) {
		Goods goods = new Goods(goodsOperationDTO);
		// 检查商品
		this.checkGoods(goods);
		if ("1".equals(goodsOperationDTO.getSalesArea()) && goods.getStoreId() != null) {
			String regionId = goodsOperationDTO.getRegionId();
			String[] split1 = regionId.split(",");
			Region region = regionService.getById(split1[split1.length - 1]);
			if (ObjectUtil.isNotEmpty(region)) {
				goods.setAdressCode(region.getAdCode());
				String center = region.getCenter();
				String[] split = center.split(",");
				goods.setLon(split[0]);
				goods.setLat(split[1]);
			}
			/*
			 * Store store = storeService.getById(goods.getStoreId()); if(store != null ){
			 * goods.setStoreAddressIdPath(store.getStoreAddressIdPath());
			 * goods.setStoreAddressPath(store.getStoreAddressPath()); }
			 */
		} else {
			goods.setStoreAddressIdPath("");
			goods.setStoreAddressPath("");
		}
		// 向goods加入图片
		// this.setGoodsGalleryParam(goodsOperationDTO.getGoodsGalleryList().get(0),
		// goods);
		// 添加商品参数
		if (goodsOperationDTO.getGoodsParamsDTOList() != null && !goodsOperationDTO.getGoodsParamsDTOList().isEmpty()) {
			// 给商品参数填充值
			goods.setParams(JSONUtil.toJsonStr(goodsOperationDTO.getGoodsParamsDTOList()));
		}
		if (goodsOperationDTO.getSkuList() != null && !goodsOperationDTO.getSkuList().isEmpty()) {
			double minValue = Double.parseDouble((String) goodsOperationDTO.getSkuList().get(0).get("price"));
			for (int i = 0; i < goodsOperationDTO.getSkuList().size(); i++) {
				if (i == goodsOperationDTO.getSkuList().size() - 1) {
					continue;
				}
				double next = Double.parseDouble((String) goodsOperationDTO.getSkuList().get(i + 1).get("price"));
				if (minValue > next) {
					minValue = next;
				}
			}
			goods.setPrice(minValue);

		}
		// 判断商品是否初审
		AuthUser authUser = UserContext.getCurrentUser();
		String memberId = authUser.getMemberId();
		QueryWrapper<Extension> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("member_id", memberId);
		objectQueryWrapper.eq("delete_flag", false);
		List<Extension> list = eextensionService.list(objectQueryWrapper);
		if (list.size() > 0) {
			Extension extension = list.get(0);
			Member promotionCode = memberService
					.getOne(new QueryWrapper<Member>().eq("promotion_code", extension.getExtension()));
			if (promotionCode != null) {
				QueryWrapper<Partner> partnersWrapper = new QueryWrapper<>();
				partnersWrapper.eq("member_id", promotionCode.getId());
				partnersWrapper.eq("delete_flag", false);
				List<Partner> partners = partnerService.list(partnersWrapper);
				if (partners.size() > 0) {
					Integer partnerType = partners.get(0).getPartnerType();
					if (partnerType != null && partnerType == 1 || partnerType == 4) {
						goods.setAuthFlag(GoodsAuthEnum.FIRSTTRIAL.name()); // 初审
					}
				}
			}
		}
		if (goodsOperationDTO.getGoodsGalleryList().size() > 0) {
			goods.setThumbnail(goodsOperationDTO.getGoodsGalleryList().get(0));
			goods.setOriginal(goodsOperationDTO.getGoodsGalleryList().get(0));
			goods.setSmall(goodsOperationDTO.getGoodsGalleryList().get(0));
		}
		// 添加商品
		this.save(goods);
		// 添加商品sku信息
		this.goodsSkuService.add(goodsOperationDTO.getSkuList(), goods);
		// 添加相册
		if (goodsOperationDTO.getGoodsGalleryList() != null && !goodsOperationDTO.getGoodsGalleryList().isEmpty()) {
			this.goodsGalleryService.add(goodsOperationDTO.getGoodsGalleryList(), goods.getId());
		}
	}

	@Override
	public void editGoods(GoodsOperationDTO goodsOperationDTO, String goodsId) {
		Goods goods = new Goods(goodsOperationDTO);
		goods.setId(goodsId);
		// 检查商品信息
		this.checkGoods(goods);
		if ("1".equals(goodsOperationDTO.getSalesArea()) && goods.getStoreId() != null) {
			Store store = storeService.getById(goods.getStoreId());
			if (store != null) {
				String regionId = goodsOperationDTO.getRegionId();
				String[] split1 = regionId.split(",");
				Region region = regionService.getById(split1[split1.length - 1]);
				if (ObjectUtil.isNotEmpty(region)) {
					goods.setAdressCode(region.getAdCode());
					String center = region.getCenter();
					String[] split = center.split(",");
					goods.setLon(split[0]);
					goods.setLat(split[1]);
				}
				/*
				 * goods.setStoreAddressIdPath(store.getStoreAddressIdPath());
				 * goods.setStoreAddressPath(store.getStoreAddressPath());
				 */
			}
		} else {
			goods.setStoreAddressIdPath("");
			goods.setStoreAddressPath("");
		}
		// 向goods加入图片
		// this.setGoodsGalleryParam(goodsOperationDTO.getGoodsGalleryList().get(0),
		// goods);
		// 添加商品参数
		if (goodsOperationDTO.getGoodsParamsDTOList() != null && !goodsOperationDTO.getGoodsParamsDTOList().isEmpty()) {
			goods.setParams(JSONUtil.toJsonStr(goodsOperationDTO.getGoodsParamsDTOList()));
		}
		if (goodsOperationDTO.getSkuList() != null && !goodsOperationDTO.getSkuList().isEmpty()) {
			double minValue = Double.parseDouble((String) goodsOperationDTO.getSkuList().get(0).get("price"));
			for (int i = 0; i < goodsOperationDTO.getSkuList().size(); i++) {
				if (i == goodsOperationDTO.getSkuList().size() - 1) {
					continue;
				}
				double next = Double.parseDouble((String) goodsOperationDTO.getSkuList().get(i + 1).get("price"));
				if (minValue > next) {
					minValue = next;
				}
			}
			goods.setPrice(minValue);

		}
		List<String> goodsGalleryList = goodsOperationDTO.getGoodsGalleryList();
		if (goodsGalleryList.size() > 0) {
			goods.setThumbnail(goodsOperationDTO.getGoodsGalleryList().get(0));
			goods.setOriginal(goodsOperationDTO.getGoodsGalleryList().get(0));
			goods.setSmall(goodsOperationDTO.getGoodsGalleryList().get(0));
		}
		// 修改商品
		this.updateById(goods);
		// 修改商品sku信息
		this.goodsSkuService.update(goodsOperationDTO.getSkuList(), goods, goodsOperationDTO.getRegeneratorSkuFlag());
		// 添加相册
		if (goodsOperationDTO.getGoodsGalleryList() != null && !goodsOperationDTO.getGoodsGalleryList().isEmpty()) {
			this.goodsGalleryService.add(goodsOperationDTO.getGoodsGalleryList(), goods.getId());
		}
		if (GoodsAuthEnum.TOBEAUDITED.name().equals(goods.getAuthFlag())) {
			this.deleteEsGoods(Collections.singletonList(goodsId));
		}
		cache.remove(CachePrefix.GOODS.getPrefix() + goodsId);
	}

	@Override
	public GoodsVO getGoodsVO(String goodsId) {
		// 缓存获取，如果没有则读取缓存
		GoodsVO goodsVO = null;
		if (goodsVO != null) {
			return goodsVO;
		}
		// 查询商品信息
		Goods goods = this.getById(goodsId);
		if (goods == null) {
			log.error("商品ID为" + goodsId + "的商品不存在");
			throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
		}
		goodsVO = new GoodsVO();
		// 赋值
		BeanUtils.copyProperties(goods, goodsVO);
		// 商品id
		goodsVO.setId(goods.getId());
		goodsVO.setRegion(goods.getStoreAddressPath());
		goodsVO.setRegionId(goods.getStoreAddressIdPath());
		// 商品相册赋值
		List<String> images = new ArrayList<>();
		List<GoodsGallery> galleryList = goodsGalleryService.goodsGalleryList(goodsId);
		for (GoodsGallery goodsGallery : galleryList) {
			images.add(goodsGallery.getOriginal());
		}
		goodsVO.setGoodsGalleryList(images);
		// 商品sku赋值
		List<GoodsSkuVO> goodsListByGoodsId = goodsSkuService.getGoodsListByGoodsId(goodsId);
		if (goodsListByGoodsId != null && !goodsListByGoodsId.isEmpty()) {
			goodsVO.setSkuList(goodsListByGoodsId);
		}
		// 商品分类名称赋值
		List<String> categoryName = new ArrayList<>();
		String categoryPath = goods.getCategoryPath();
		String[] strArray = categoryPath.split(",");
		List<Category> categories = categoryService.listByIds(Arrays.asList(strArray));
		for (Category category : categories) {
			categoryName.add(category.getName());
		}
		goodsVO.setCategoryName(categoryName);

		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("ag.goods_id", goodsId);
		queryWrapper.lt("a.activity_start_time", new Date());
		queryWrapper.gt("a.activity_end_time", new Date());
		queryWrapper.eq("a.delete_flag", false);
		ActivityVO activityVO = activityMapper.getAppActivityById(queryWrapper);
		if (activityVO != null) {
			goodsVO.setQuantityFlag(activityVO.getQuantityFlag());
			goodsVO.setQuantity(activityVO.getQuantity());
		}

		// 参数非空则填写参数
		if (CharSequenceUtil.isNotEmpty(goods.getParams())) {
			goodsVO.setGoodsParamsDTOList(JSONUtil.toList(goods.getParams(), GoodsParamsDTO.class));
		}
		cache.put(CachePrefix.GOODS.getPrefix() + goodsId, goodsVO);
		return goodsVO;
	}

	@Override
	public IPage<GoodsVO> queryByParams(GoodsSearchParams goodsSearchParams) {
		// return this.page(PageUtil.initPage(goodsSearchParams),
		// goodsSearchParams.queryWrapper());
		AuthUser currentUser = UserContext.getCurrentUser();
		LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
		lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
		lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
		lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
		Partner partner = partnerService.getOne(lambdaQueryWrapper);
		if (null != partner && cn.lili.common.utils.StringUtils.isNotEmpty(partner.getRegionId())) {
			goodsSearchParams.setAdCodeList(regionService.getPartnerAdCode(partner.getRegionId(), "4"));
		}
		goodsSearchParams.setGroupBySort(true);
		QueryWrapper<GoodsSearchParams> objectQueryWrapper = goodsSearchParams.queryWrapper();
		objectQueryWrapper.in("s.store_disable", StoreStatusEnum.OPEN.name(), StoreStatusEnum.CLOSED.name());
		IPage<GoodsVO> goodsVOIPage = baseMapper.queryByParams(PageUtil.initPage(goodsSearchParams),
			objectQueryWrapper);
		if (CollectionUtils.isNotEmpty(goodsVOIPage.getRecords())) {
			for (GoodsVO goodsVO : goodsVOIPage.getRecords()) {
				// 商品相册赋值
				List<String> images = new ArrayList<>();
				List<GoodsGallery> galleryList = goodsGalleryService.goodsGalleryList(goodsVO.getId());
				for (GoodsGallery goodsGallery : galleryList) {
					images.add(goodsGallery.getOriginal());
				}
				goodsVO.setGoodsGalleryList(images);
			}
		}
		return goodsVOIPage;
	}

	/**
	 * 商品查询
	 *
	 * @param goodsSearchParams
	 *            查询参数
	 * @return 商品信息
	 */
	@Override
	public List<Goods> queryListByParams(GoodsSearchParams goodsSearchParams) {
		return this.list(goodsSearchParams.queryWrapper());
	}

	@Override
	public boolean auditGoods(List<String> goodsIds, GoodsAuthEnum goodsAuthEnum, String authMessage) {
		boolean result = false;
		for (String goodsId : goodsIds) {
			Goods goods = this.checkExist(goodsId);
			goods.setAuthFlag(goodsAuthEnum.name());
			if (StringUtils.isNotEmpty(authMessage))
				goods.setAuthMessage(authMessage);
			result = this.updateById(goods);
			goodsSkuService.updateGoodsSkuStatus(goods);
			// 删除之前的缓存
			cache.remove(CachePrefix.GOODS.getPrefix() + goodsId);
			// 商品审核消息
			String destination = rocketmqCustomProperties.getGoodsTopic() + ":" + GoodsTagsEnum.GOODS_AUDIT.name();
			// 发送mq消息
			rocketMQTemplate.asyncSend(destination, JSONUtil.toJsonStr(goods),
					RocketmqSendCallbackBuilder.commonCallback());
		}
		return result;
	}

	@Override
	public Boolean updateGoodsMarketAble(List<String> goodsIds, GoodsStatusEnum goodsStatusEnum, String underReason) {
		boolean result;

		// 如果商品为空，直接返回
		if (goodsIds == null || goodsIds.isEmpty()) {
			return true;
		}

		LambdaUpdateWrapper<Goods> updateWrapper = this.getUpdateWrapperByStoreAuthority();
		updateWrapper.set(Goods::getMarketEnable, goodsStatusEnum.name());
		updateWrapper.set(Goods::getUnderMessage, underReason);
		updateWrapper.in(Goods::getId, goodsIds);
		result = this.update(updateWrapper);

		// 修改规格商品
		LambdaQueryWrapper<Goods> queryWrapper = this.getQueryWrapperByStoreAuthority();
		queryWrapper.in(Goods::getId, goodsIds);
		List<Goods> goodsList = this.list(queryWrapper);
		for (Goods goods : goodsList) {
			goodsSkuService.updateGoodsSkuStatus(goods);
		}

		if (GoodsStatusEnum.DOWN.equals(goodsStatusEnum)) {
			this.deleteEsGoods(goodsIds);
		}
		return result;
	}

	@Override
	public Boolean managerUpdateGoodsMarketAble(List<String> goodsIds, GoodsStatusEnum goodsStatusEnum,
			String underReason) {
		boolean result;

		// 如果商品为空，直接返回
		if (goodsIds == null || goodsIds.isEmpty()) {
			return true;
		}

		// 检测管理员权限
		this.checkManagerAuthority();

		LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.set(Goods::getMarketEnable, goodsStatusEnum.name());
		updateWrapper.set(Goods::getUnderMessage, underReason);
		updateWrapper.in(Goods::getId, goodsIds);
		result = this.update(updateWrapper);

		// 修改规格商品
		LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(Goods::getId, goodsIds);
		List<Goods> goodsList = this.list(queryWrapper);
		for (Goods goods : goodsList) {
			goodsSkuService.updateGoodsSkuStatus(goods);
		}
		if (GoodsStatusEnum.DOWN.equals(goodsStatusEnum)) {
			this.deleteEsGoods(goodsIds);
		}
		return result;
	}

	@Override
	public Boolean deleteGoods(List<String> goodsIds) {

		LambdaUpdateWrapper<Goods> updateWrapper = this.getUpdateWrapperByStoreAuthority();
		updateWrapper.set(Goods::getMarketEnable, GoodsStatusEnum.DOWN.name());
		updateWrapper.set(Goods::getDeleteFlag, true);
		updateWrapper.in(Goods::getId, goodsIds);
		this.update(updateWrapper);

		// 修改规格商品
		LambdaQueryWrapper<Goods> queryWrapper = this.getQueryWrapperByStoreAuthority();
		queryWrapper.in(Goods::getId, goodsIds);
		List<Goods> goodsList = this.list(queryWrapper);
		for (Goods goods : goodsList) {
			// 修改SKU状态
			goodsSkuService.updateGoodsSkuStatus(goods);
		}

		this.deleteEsGoods(goodsIds);

		return true;
	}

	@Override
	public Boolean freight(List<String> goodsIds, String templateId) {

		AuthUser authUser = this.checkStoreAuthority();

		FreightTemplate freightTemplate = freightTemplateService.getById(templateId);
		if (freightTemplate == null) {
			throw new ServiceException(ResultCode.FREIGHT_TEMPLATE_NOT_EXIST);
		}
		if (authUser != null && !freightTemplate.getStoreId().equals(authUser.getStoreId())) {
			throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
		}
		LambdaUpdateWrapper<Goods> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
		lambdaUpdateWrapper.set(Goods::getTemplateId, templateId);
		lambdaUpdateWrapper.in(Goods::getId, goodsIds);
		return this.update(lambdaUpdateWrapper);
	}

	@Override
	public void updateStock(String goodsId, Integer quantity) {
		LambdaUpdateWrapper<Goods> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
		lambdaUpdateWrapper.set(Goods::getQuantity, quantity);
		lambdaUpdateWrapper.eq(Goods::getId, goodsId);
		this.update(lambdaUpdateWrapper);
	}

	@Override
	public void updateGoodsCommentNum(String goodsId) {

		// 获取商品信息
		Goods goods = this.getById(goodsId);
		// 修改商品评价数量
		goods.setCommentNum(goods.getCommentNum() + 1);

		// 修改商品好评率
		LambdaQueryWrapper<MemberEvaluation> goodEvaluationQueryWrapper = new LambdaQueryWrapper<>();
		goodEvaluationQueryWrapper.eq(MemberEvaluation::getId, goodsId);
		goodEvaluationQueryWrapper.eq(MemberEvaluation::getGrade, EvaluationGradeEnum.GOOD.name());
		// 好评数量
		long highPraiseNum = memberEvaluationService.count(goodEvaluationQueryWrapper);
		// 好评率
		double grade = NumberUtil.mul(NumberUtil.div(highPraiseNum, goods.getCommentNum().doubleValue(), 2), 100);
		goods.setGrade(grade);
		this.updateById(goods);
	}

	/**
	 * 更新商品的购买数量
	 *
	 * @param goodsId
	 *            商品ID
	 * @param buyCount
	 *            购买数量
	 */
	@Override
	public void updateGoodsBuyCount(String goodsId, int buyCount) {
		this.update(new LambdaUpdateWrapper<Goods>().eq(Goods::getId, goodsId).set(Goods::getBuyCount, buyCount));
	}

	@Override
	public void updateStoreDetail(Store store) {
		UpdateWrapper updateWrapper = new UpdateWrapper<>().eq("store_id", store.getId())
				.set("store_name", store.getStoreName()).set("self_operated", store.getSelfOperated());
		this.update(updateWrapper);
		goodsSkuService.update(updateWrapper);
	}

	@Override
	public long countStoreGoodsNum(String storeId) {
		return this.count(new LambdaQueryWrapper<Goods>().eq(Goods::getStoreId, storeId)
				.eq(Goods::getAuthFlag, GoodsAuthEnum.PASS.name())
				.eq(Goods::getMarketEnable, GoodsStatusEnum.UPPER.name()));
	}

	@Override
	public void importBatchTemplate(HttpServletResponse response) {
		ExcelUtil<BatchGoodsImportVo> util = new ExcelUtil<BatchGoodsImportVo>(BatchGoodsImportVo.class);
		util.importTemplateExcel(response, "商品批量导入模板", "商品批量导入模板");
	}

	@Override
	public void importBatch(MultipartFile file) throws Exception {
		ExcelUtil<BatchGoodsImportVo> util = new ExcelUtil<BatchGoodsImportVo>(BatchGoodsImportVo.class);
		final List<BatchGoodsImportVo> batchGoodsImportVos = util.importExcel(file.getInputStream());

		final String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId();
		// final String storeId = "1507898094845648897";

		// 查询店家所有的图片
		final Map<String, String> imageMap = goodsImgDictService
				.list(new LambdaQueryWrapper<GoodsImgDict>().eq(GoodsImgDict::getStoreId, storeId)).stream()
				.collect(Collectors.toMap(GoodsImgDict::getImgName, GoodsImgDict::getImgUrl, (i1, i2) -> i2));

		// 获取店铺经营范围
		// String goodsManagementCategory =
		// storeDetailService.getStoreDetail(storeId).getGoodsManagementCategory();
		final Map<String, String> categoryPathMap = categoryService.list().stream()
				.collect(Collectors.toMap(Category::getName, BaseEntity::getId, (i1, i2) -> i1));

		// 如果sku商品没有图片，用主图图片
		batchGoodsImportVos.forEach(batchGoodsImportVo -> {
			final String sku = batchGoodsImportVo.getSku();

			final String[] goodsGalleryArr = batchGoodsImportVo.getGoodsGallery().split(";");

			if (goodsGalleryArr.length > 0) {

				final String goodsUrl = imageMap.get(goodsGalleryArr[0]);
				if (StringUtils.isNotBlank(goodsUrl) && StringUtils.isNotBlank(batchGoodsImportVo.getFirstCategory())
						&& StringUtils.isNotBlank(batchGoodsImportVo.getSecondCategory())
						&& StringUtils.isNotBlank(batchGoodsImportVo.getThirdCategory())
						&& StringUtils.isNotBlank(categoryPathMap.get(batchGoodsImportVo.getFirstCategory()))
						&& StringUtils.isNotBlank(categoryPathMap.get(batchGoodsImportVo.getSecondCategory()))
						&& StringUtils.isNotBlank(categoryPathMap.get(batchGoodsImportVo.getThirdCategory()))) {
					List<String> goodsGalleryList = new LinkedList<>();
					batchGoodsImportVo.setGoodsGalleryList(goodsGalleryList);
					for (String url : goodsGalleryArr) {
						final String s = imageMap.get(url);
						if (StringUtils.isNotBlank(s)) {
							goodsGalleryList.add(s);
						}
					}

					batchGoodsImportVo.setCategoryPath(
							String.join(",", categoryPathMap.get(batchGoodsImportVo.getFirstCategory()),
									categoryPathMap.get(batchGoodsImportVo.getSecondCategory()),
									categoryPathMap.get(batchGoodsImportVo.getThirdCategory())));

					Goods goods = new Goods(batchGoodsImportVo);
					// 检查商品
					this.checkGoods(goods);
					// 向goods加入图片
					this.setGoodsGalleryParam(goodsUrl, goods);
					// 添加商品参数
					// if (goodsOperationDTO.getGoodsParamsDTOList() != null &&
					// !goodsOperationDTO.getGoodsParamsDTOList().isEmpty()) {
					// //给商品参数填充值
					// goods.setParams(JSONUtil.toJsonStr(goodsOperationDTO.getGoodsParamsDTOList()));
					// }

					// //添加商品sku信息
					// 规格名=规格值&规格名=规格值，重量，货号，库存，成本价，价格，图片（图片之间&号分割））规格之间英文分号分割
					List<Map<String, Object>> skuList = new LinkedList<>();
					final String[] splitGuiGeXiang = sku.split(";");
					for (String guigeXiang : splitGuiGeXiang) {
						final String[] split = guigeXiang.split(",");
						System.out.println("sku--切分数量" + split.length);
						if (split.length == 7) {
							Map<String, Object> map = new HashMap<>();
							// 规格名=规格值&规格名=规格值
							final String[] guige = split[0].split("&");
							for (String str : guige) {
								final String[] sp = str.split("=");
								map.put(sp[0], sp[1]);
							}
							// 重量
							map.put("weight", split[1]);
							// 货号
							map.put("sn", split[2]);
							// 库存
							map.put("quantity", split[3]);
							map.put("cost", split[4]);
							map.put("price", split[5]);
							final String urlStr = split[6];
							if (StringUtils.isNotBlank(urlStr)) {
								List<Map<String, String>> images = new LinkedList<>();
								final String[] imgarr = urlStr.split("&");
								for (String img : imgarr) {
									Map<String, String> imgMap = new HashMap<>();
									if (StringUtils.isNotBlank(imageMap.get(img))) {
										imgMap.put("url", imageMap.get(img));
										images.add(imgMap);
									}
								}

								map.put("images", images);
							}
							skuList.add(map);

						} else {
							log.error("店铺id：" + storeId + " 的商品：" + batchGoodsImportVo.getGoodsName()
									+ " sku切分个数错误，切分数量为：" + split.length + " 切分内容为：" + guigeXiang);
						}

					}

					// 添加商品
					this.save(goods);
					this.goodsSkuService.add(skuList, goods);
					// 添加相册
					if (batchGoodsImportVo.getGoodsGalleryList() != null
							&& !batchGoodsImportVo.getGoodsGalleryList().isEmpty()) {
						this.goodsGalleryService.add(batchGoodsImportVo.getGoodsGalleryList(), goods.getId());
					}

				} else {
					log.error("店铺id：" + storeId + " 的商品：" + batchGoodsImportVo.getGoodsName() + " 图片缺失");
				}

			} else {
				log.error("店铺id：" + storeId + " 的商品：" + batchGoodsImportVo.getGoodsName() + " 图片缺失");
			}

		});

	}

	@Override
	public List<ImportResult> importBatchNew(MultipartFile file) throws Exception {
		// 读取产品数据
		ExcelUtil<GoodsSpuImportVo> spuUtil = new ExcelUtil<>(GoodsSpuImportVo.class);
		List<GoodsSpuImportVo> goodsSpuImportVoList = spuUtil.importExcel("产品", file.getInputStream(), 0);

		// 读取产品规格数据
		ExcelUtil<GoodsSkuImportVo> skuUtil = new ExcelUtil<>(GoodsSkuImportVo.class);
		List<GoodsSkuImportVo> goodsSkuImportVoList = skuUtil.importExcel("产品规格", file.getInputStream(), 0);
		Map<String, List<GoodsSkuImportVo>> goodsSkuImportMap = goodsSkuImportVoList.stream()
				.collect(Collectors.groupingBy(GoodsSkuImportVo::getGoodsNo));

		// 店铺全部图片
		Map<String, String> goodsImgDictMap = getGoodsImgMap();

		// 全部分类
		Map<String, String> categoryMap = getCategoryMap();

		// 店铺信息
		Store store = getStore();

		// 配置
		GoodsSetting setting = getSetting();

		// 导入结果列表
		List<ImportResult> importResultList = new ArrayList<>(goodsSpuImportVoList.size());

		GOOD : for (GoodsSpuImportVo goodsSpuImportVo : goodsSpuImportVoList) {

			// 导入结果
			ImportResult importResult = new ImportResult();

			goodsSpuImportVo.setGoodsImgDictMap(goodsImgDictMap);
			goodsSpuImportVo.setCategoryMap(categoryMap);
			goodsSpuImportVo.setStore(store);
			goodsSpuImportVo.setGoodsSetting(setting);
			Goods goods = importResult.getGoods(goodsSpuImportVo);
			if (goods == null) {
				importResultList.add(importResult);
				continue;
			}
			if (StrUtil.isNotBlank(goodsSpuImportVo.getTemplateName())) {
				FreightTemplate template = freightTemplateService
						.getFreightTemplateAndStore(goodsSpuImportVo.getTemplateName(), store.getId());
				if (template != null) {
					goods.setTemplateId(template.getId());
				}
			}

			List<GoodsSkuImportVo> skuListBySpu = goodsSkuImportMap.get(goodsSpuImportVo.getGoodsNo());
			if (skuListBySpu == null || skuListBySpu.isEmpty()) {
				importResult.setState("导入失败");
				importResult.setErrorCause("产品规格为空");
				importResultList.add(importResult);
				continue;
			}

			List<GoodsSku> goodsSkuList = new ArrayList<>();
			GoodsSku minPrice = null;
			for (GoodsSkuImportVo goodsSkuImportVo : skuListBySpu) {
				goodsSkuImportVo.setGoodsImgDictMap(goodsImgDictMap);
				goodsSkuImportVo.setGoods(goods);
				GoodsSku goodsSku = importResult.getGoodsSku(goodsSkuImportVo);
				if (goodsSku == null) {
					importResultList.add(importResult);
					continue GOOD;
				}
				// 获取价格最低的sku数据放入spu
				if (minPrice != null) {
					Double minPriceDou = minPrice.getPrice();
					Double skuPrice = goodsSku.getPrice();
					if (minPriceDou > skuPrice) {
						minPrice = goodsSku;
					}
				} else {
					minPrice = goodsSku;
				}
				goodsSkuList.add(goodsSku);
			}

			// 总库存
			int sum = goodsSkuList.stream().mapToInt(GoodsSku::getQuantity).sum();
			goods.setQuantity(sum);
			goods.setPrice(minPrice.getPrice());

			// 添加商品
			save(goods);
			for (GoodsSku goodsSku : goodsSkuList) {
				goodsSku.setGoodsId(goods.getId());
			}
			goodsSkuService.saveBatch(goodsSkuList);
			goodsSkuService.generateEs(goods);

			// 添加相册
			if (goodsSpuImportVo.getGoodsGalleryList() != null && !goodsSpuImportVo.getGoodsGalleryList().isEmpty()) {
				this.goodsGalleryService.add(goodsSpuImportVo.getGoodsGalleryList(), goods.getId());
			}
			importResult.setState("导入成功");
			importResult.setErrorCause("导入成功");
			importResultList.add(importResult);
		}
		return importResultList;
	}

	private Map<String, String> getGoodsImgMap() {
		String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId();
		LambdaQueryWrapper<GoodsImgDict> queryWrapper = new LambdaQueryWrapper<GoodsImgDict>()
				.eq(GoodsImgDict::getStoreId, storeId);
		List<GoodsImgDict> goodsImgDictList = goodsImgDictService.list(queryWrapper);
		return goodsImgDictList.stream()
				.collect(Collectors.toMap(GoodsImgDict::getImgName, GoodsImgDict::getImgUrl, (i1, i2) -> i2));
	}

	private Map<String, String> getCategoryMap() {
		List<Category> list = categoryService.list();
		return list.stream().collect(Collectors.toMap(Category::getName, Category::getId, (i1, i2) -> i1));
	}

	private Store getStore() {
		String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId();
		return storeService.getById(storeId);
	}

	private GoodsSetting getSetting() {
		Setting setting = settingService.get(SettingEnum.GOODS_SETTING.name());
		return JSONUtil.toBean(setting.getSettingValue(), GoodsSetting.class);
	}

	@Override
	public Boolean updateRecommend(String good, Boolean recommend, int recommendRanking) {
		return this.baseMapper.updateRecommend(good, recommend, recommendRanking);
	}

	@Override
	public Boolean updateSort(String good, Long sort) {
		return this.baseMapper.updateSort(good, sort);
	}

	@Override
	public IPage<EsStoreIndexVO> geStoreInfoByData(EsStoreIndexDTO esStoreIndexDTO) {
		IPage<EsStoreIndexVO> goodsByStore = goodsMapper.geStoreInfoByData(PageUtil.initPage(esStoreIndexDTO),
				esStoreIndexDTO.queryWrapper());
		return goodsByStore;
	}

	@Override
	public Boolean updateSortGoods(String goodsId, int num) {
		return goodsMapper.updateSortGoods(goodsId, num);
	}

	@Override
	public IPage<EsGoodsIndexVO> getGoodsByStore(EsGoodsIndexDTO esGoodsIndexDTO) {
		// 修改商品查询的排序
		if (StringUtils.isNotEmpty(esGoodsIndexDTO.getType()) && esGoodsIndexDTO.getType().equals("销量")) {
			esGoodsIndexDTO.setMonthSales(1);
		} else if (StringUtils.isNotEmpty(esGoodsIndexDTO.getType()) && esGoodsIndexDTO.getType().equals("评分")) {
			esGoodsIndexDTO.setScore(1.0);
		} else if (StringUtils.isNotEmpty(esGoodsIndexDTO.getType()) && esGoodsIndexDTO.getType().equals("价格升")) {
			esGoodsIndexDTO.setPriceAsc(1.0);
		} else if (StringUtils.isNotEmpty(esGoodsIndexDTO.getType()) && esGoodsIndexDTO.getType().equals("价格降")) {
			esGoodsIndexDTO.setPriceDesc(1.0);
		}
		IPage<EsGoodsIndexVO> goodsByStore = goodsMapper.getGoodsByStore(PageUtil.initPage(esGoodsIndexDTO),
				esGoodsIndexDTO.queryWrapper());
		for (EsGoodsIndexVO esGoodsIndexVO : goodsByStore.getRecords()) {
			esGoodsIndexVO.setMemberPrice(getGoodsSkuService.countMemberPrice(esGoodsIndexVO.getPrice()));

			// 商品sku赋值
			List<GoodsSkuVO> goodsListByGoodsId = goodsSkuService.getGoodsListByGoodsId(esGoodsIndexVO.getId());
			if (goodsListByGoodsId != null && !goodsListByGoodsId.isEmpty()) {
				esGoodsIndexVO.setSkuList(goodsListByGoodsId);
			}
		}
		return goodsByStore;
	}

	/**
	 * 发送删除es索引的信息
	 *
	 * @param goodsIds
	 *            商品id
	 */
	private void deleteEsGoods(List<String> goodsIds) {
		// 商品删除消息
		String destination = rocketmqCustomProperties.getGoodsTopic() + ":" + GoodsTagsEnum.GOODS_DELETE.name();
		// 发送mq消息
		rocketMQTemplate.asyncSend(destination, JSONUtil.toJsonStr(goodsIds),
				RocketmqSendCallbackBuilder.commonCallback());
	}

	/**
	 * 添加商品默认图片
	 *
	 * @param origin
	 *            图片
	 * @param goods
	 *            商品
	 */
	private void setGoodsGalleryParam(String origin, Goods goods) {
		GoodsGallery goodsGallery = goodsGalleryService.getGoodsGallery(origin);
		goods.setOriginal(goodsGallery.getOriginal());
		goods.setSmall(goodsGallery.getSmall());
		goods.setThumbnail(goodsGallery.getThumbnail());
	}

	/**
	 * 检查商品信息 如果商品是虚拟商品则无需配置配送模板 如果商品是实物商品需要配置配送模板 判断商品是否存在 判断商品是否需要审核 判断当前用户是否为店铺
	 *
	 * @param goods
	 *            商品
	 */
	private void checkGoods(Goods goods) {
		// 判断商品类型
		switch (goods.getGoodsType()) {
			case "PHYSICAL_GOODS" :
				if ("0".equals(goods.getTemplateId())) {
					throw new ServiceException(ResultCode.PHYSICAL_GOODS_NEED_TEMP);
				}
				break;
			case "VIRTUAL_GOODS" :
				if (!"0".equals(goods.getTemplateId())) {
					throw new ServiceException(ResultCode.VIRTUAL_GOODS_NOT_NEED_TEMP);
				}
				break;
			default :
				throw new ServiceException(ResultCode.GOODS_TYPE_ERROR);
		}
		// 检查商品是否存在--修改商品时使用
		if (goods.getId() != null) {
			this.checkExist(goods.getId());
		} else {
			// 评论次数
			goods.setCommentNum(0);
			// 购买次数
			goods.setBuyCount(0);
			// 购买次数
			goods.setQuantity(0);
			// 商品评分
			goods.setGrade(100.0);
		}

		// 获取商品系统配置决定是否审核
		Setting setting = settingService.get(SettingEnum.GOODS_SETTING.name());
		GoodsSetting goodsSetting = JSONUtil.toBean(setting.getSettingValue(), GoodsSetting.class);
		// 是否需要审核
		goods.setAuthFlag(Boolean.TRUE.equals(goodsSetting.getGoodsCheck())
				? GoodsAuthEnum.TOBEAUDITED.name()
				: GoodsAuthEnum.PASS.name());
		// 判断当前用户是否为店铺
		Member member = memberService.getById(Objects.requireNonNull(UserContext.getCurrentUser()).getMemberId());
		if (member == null) {
			throw new ServiceException(ResultCode.STORE_NOT_LOGIN_ERROR);
		}
		Boolean haveStore = member.getHaveStore();
		if (Objects.requireNonNull(UserContext.getCurrentUser()).getRole().equals(UserEnums.STORE) || haveStore) {
			StoreVO storeDetail = this.storeService.getStoreDetail();
			if (storeDetail.getSelfOperated() != null) {
				goods.setSelfOperated(storeDetail.getSelfOperated() == 1 ? true : false);
			}
			goods.setStoreId(storeDetail.getId());
			goods.setStoreName(storeDetail.getStoreName());
		} else {
			throw new ServiceException(ResultCode.STORE_NOT_LOGIN_ERROR);
		}
	}

	/**
	 * 判断商品是否存在
	 *
	 * @param goodsId
	 *            商品id
	 * @return 商品信息
	 */
	private Goods checkExist(String goodsId) {
		Goods goods = getById(goodsId);
		if (goods == null) {
			log.error("商品ID为" + goodsId + "的商品不存在");
			throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
		}
		return goods;
	}

	/**
	 * 获取UpdateWrapper（检查用户越权）
	 *
	 * @return updateWrapper
	 */
	private LambdaUpdateWrapper<Goods> getUpdateWrapperByStoreAuthority() {
		LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
		AuthUser authUser = this.checkStoreAuthority();
		if (authUser != null) {
			updateWrapper.eq(Goods::getStoreId, authUser.getStoreId());
		}
		return updateWrapper;
	}

	/**
	 * 检查当前登录的店铺
	 *
	 * @return 当前登录的店铺
	 */
	private AuthUser checkStoreAuthority() {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为店铺角色
		if (currentUser != null
				&& (currentUser.getRole().equals(UserEnums.STORE) && currentUser.getStoreId() != null)) {
			return currentUser;
		}
		return null;
	}

	/**
	 * 检查当前登录的店铺
	 *
	 * @return 当前登录的店铺
	 */
	private AuthUser checkManagerAuthority() {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为店铺角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.MANAGER))) {
			return currentUser;
		} else {
			throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
		}
	}

	/**
	 * 获取QueryWrapper（检查用户越权）
	 *
	 * @return queryWrapper
	 */
	private LambdaQueryWrapper<Goods> getQueryWrapperByStoreAuthority() {
		LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
		AuthUser authUser = this.checkStoreAuthority();
		if (authUser != null) {
			queryWrapper.eq(Goods::getStoreId, authUser.getStoreId());
		}
		return queryWrapper;
	}

	@Override
	public IPage<GoodsVO> getGoodsListByPage(String goodsId, PageVO page) {
		IPage<GoodsVO> goodsListByPage = this.baseMapper.getGoodsListByPage(PageUtil.initPage(page), goodsId);
		if (CollectionUtils.isNotEmpty(goodsListByPage.getRecords())) {
			for (GoodsVO goodsVO : goodsListByPage.getRecords()) {
				// 商品sku赋值
				List<GoodsSkuVO> goodsListByGoodsId = goodsSkuService.getGoodsListByGoodsId(goodsId);
				if (goodsListByGoodsId != null && !goodsListByGoodsId.isEmpty()) {
					goodsVO.setSkuList(goodsListByGoodsId);
				}
			}
		}
		return goodsListByPage;
	}

	@Override
	public List<GoodsVO> getGoodsByActivityId(String activityId, String storeId) {
		return goodsMapper.getGoodsByActivityId(activityId, storeId);
	}

	@Override
	public List<StoreVO> getStoreByActivityId(String activityId) {
		return goodsMapper.getStoreByActivityId(activityId);
	}

	@Override
	public IPage<GoodsVO> getGoodsByStoreId(PageVO page, String storeId, String goodsName, String activityId,
			String shopCategoryPath) {
		return goodsMapper.getGoodsByStoreId(PageUtil.initPage(page), storeId, goodsName, activityId, shopCategoryPath);
	}

	@Override
	public IPage<GoodsVO> getfirstTrialPage(GoodsSearchParams goodsSearchParams) {
		// return this.page(PageUtil.initPage(goodsSearchParams),
		// goodsSearchParams.queryWrapper());
		AuthUser currentUser = UserContext.getCurrentUser();
		// 添加权限
		if (cn.lili.common.utils.StringUtils.isNotEmpty(currentUser.getMemberId())) {
			List<Member> agents = memberService.getAgents(currentUser.getMemberId());
			List<String> memberIds = new ArrayList<>();
			agents.forEach(item -> {
				if (item.getHaveStore()) {
					memberIds.add(item.getId());
				}
			});
			if (memberIds.size() > 0) {
				goodsSearchParams.setMemberIds(memberIds);
			}
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && cn.lili.common.utils.StringUtils.isNotEmpty(partner.getRegionId())) {
				goodsSearchParams.setAdCodeList(regionService.getPartnerAdCode(partner.getRegionId(), "4"));
			}
		}
		goodsSearchParams.setGroupBySort(true);
		IPage<GoodsVO> goodsVOIPage = baseMapper.queryByParams(PageUtil.initPage(goodsSearchParams),
				goodsSearchParams.queryWrapper());
		if (CollectionUtils.isNotEmpty(goodsVOIPage.getRecords())) {
			for (GoodsVO goodsVO : goodsVOIPage.getRecords()) {
				// 商品相册赋值
				List<String> images = new ArrayList<>();
				List<GoodsGallery> galleryList = goodsGalleryService.goodsGalleryList(goodsVO.getId());
				for (GoodsGallery goodsGallery : galleryList) {
					images.add(goodsGallery.getOriginal());
				}
				goodsVO.setGoodsGalleryList(images);
			}
		}
		return goodsVOIPage;
	}

	@Override
	public boolean firstTrialGoods(List<String> goodsIds, GoodsAuthEnum goodsAuthEnum, String authMessage) {
		boolean result = false;
		for (String goodsId : goodsIds) {
			Goods goods = this.checkExist(goodsId);
			goods.setAuthFlag(goodsAuthEnum.name());
			if (StringUtils.isNotEmpty(authMessage))
				goods.setAuthMessage(authMessage);
			result = this.updateById(goods);
			goodsSkuService.updateGoodsSkuStatus(goods);
			// 删除之前的缓存
			cache.remove(CachePrefix.GOODS.getPrefix() + goodsId);
			// 商品审核消息
			String destination = rocketmqCustomProperties.getGoodsTopic() + ":" + GoodsTagsEnum.GOODS_AUDIT.name();
			// 发送mq消息
			rocketMQTemplate.asyncSend(destination, JSONUtil.toJsonStr(goods),
					RocketmqSendCallbackBuilder.commonCallback());
		}
		return result;
	}

}